const useHelper = require('../../tools/helper')
const fs = require('fs')
const path = require('path')
const useCommonFun = require("../common");


/**
 * 分页获取数据
 * @param {*} params 
 * @returns 
 */
const page = async (params) => {
    try {
        // 验证参数
        validatePageParams(params)
        // 获取参数
        const { fileName, pageSize, page, columnFieldTotal, needTotalNum } = params

        const cacheFilePath = await getCacheFilePath(params)
        if (needTotalNum === false) {
            if (cacheFilePath && fs.existsSync(cacheFilePath)) {
                const cacheFileData = await getCacheFileData(cacheFilePath)
                if (cacheFileData) {
                    return cacheFileData
                }
            }
        }

        let downloadUrl = 'https://ecloud.yzhkj.cn/' + fileName;
        // let downloadUrl = 'https://ecloud.yzhkj.cn/retailReport/20250717/23857daedef9afc9f00bc3eaeef9d3a8.zip'
        // 检测文件是否存在
        const zpiPath = path.join(useHelper.TEMP_PATH, fileName)
        console.log("zpiPath", zpiPath)
        const outputDir = path.dirname(zpiPath);
        console.log("outputDir", outputDir)
        if (!fs.existsSync(outputDir)) {
            fs.mkdirSync(outputDir, { recursive: true });
        }
        // 获取json文件路径
        const jsonFilePath = zpiPath.replace(/\.zip$/, '.json');
        if (!fs.existsSync(zpiPath)) {
            if (useHelper.APP_DEBUG) {
                console.log("downloadUrl", downloadUrl)
                console.log("zpiPath", zpiPath)
            }
            await useCommonFun.downloadByUrl(zpiPath, downloadUrl)
            // 解压
            useCommonFun.unzipSync(zpiPath, outputDir)
        } else {
            if (!fs.existsSync(jsonFilePath)) {
                useCommonFun.unzipSync(zpiPath, outputDir)
            }
            if (useHelper.APP_DEBUG) {
                console.log("文件已存在！")
            }
        }
        const result = await useCommonFun.streamPageFromJson(jsonFilePath, page, pageSize, needTotalNum === true ? true : false, columnFieldTotal)
        // 保存缓存文件数据
        if (needTotalNum === false || (page === 1 && needTotalNum === true)) {
            // 如果文件不存在，则保存缓存文件数据       
            if (!fs.existsSync(cacheFilePath)) {
                console.log("cacheFilePath", cacheFilePath)
                console.log("保存缓存文件数据")
                await saveCacheFileData(cacheFilePath, result)
            }
        }
        return result
    } catch (err) {
        throw new Error(err.message);
    }

}

/**
 * 获取缓存文件路径
 * @param {*} params 
 * @returns 
 */
const getCacheFilePath = async (params) => {
    const { fileName, pageSize, page } = params
    const cacheFileName = fileName.replace(/\.zip$/, '-index')
    const cacheDir = path.join(useHelper.TEMP_PATH, cacheFileName)
    const pageIndex = page + '-' + pageSize + '.json'
    const newCacheFileName = path.join(cacheDir, pageIndex)
    if (!fs.existsSync(cacheDir)) {
        fs.mkdirSync(cacheDir, { recursive: true });
    }
    return newCacheFileName
}


/**
 * 获取缓存文件数据
 * @param {*} cacheFilePath 
 * @returns 
 */
const getCacheFileData = async (cacheFilePath) => {
    if (fs.existsSync(cacheFilePath)) {
        return JSON.parse(fs.readFileSync(cacheFilePath, 'utf8'))
    }
    return null
}


/**
 * 保存缓存文件数据
 * @param {*} filePath 
 * @param {*} data 
 * @returns 
 */
const saveCacheFileData = async (filePath, data) => {
    try {
        fs.writeFileSync(filePath, JSON.stringify(data))
        return filePath
    } catch (err) {
        throw new Error(err.message);
    }
}


/**
 * 验证分页参数
 * @param {*} params 
 * @returns 
 */
const validatePageParams = (params) => {
    const { fileName, pageSize, page, columnFieldTotal, needTotalNum } = params
    if (!fileName) {
        throw new Error('文件名称不能为空！');
    }
    if (typeof needTotalNum !== 'boolean') {
        throw new Error('needTotalNum 必须为布尔值！');
    }
    if (typeof columnFieldTotal !== 'object') {
        throw new Error('columnFieldTotal 必须为对象！');
    }
    if (typeof pageSize !== 'number') {
        throw new Error('pageSize 必须为数字！');
    }
    if (typeof page !== 'number') {
        throw new Error('page 必须为数字！');
    }

    return params
}


module.exports = {
    page
}
